Обновить

Tun2Socks: proxy server as a gateway, or VPN via proxy

Время на прочтение 9 min
Количество просмотров 36K
  1. What is Tun2Socks

  2. Instructions for Windows

  3. Instructions for Linux

In everyday use, the default gateway is specified in the network settings of your computer. Most often, the device that is the gateway is called a “router” or “router” - all requests to IP addresses that are not part of your local network go through it. A proxy server (from the English “authorized” or “trusted”) also acts as an intermediary between you and the target network resource, but is not a default gateway, that is, to use it in the application, you must explicitly specify the appropriate parameters. The simplest example is access on an I2P or Tor network. All the internal logic of these networks is provided by a separate application, which provides the user with a proxy interface for connection. By specifying the desired proxy in the web browser settings, we can visit sites with domain names ".i2p" and ".onion", which a regular router does not even know about. Also, proxy services are gaining popularity for bypassing blocking: you have registered some proxy from a liberal country in your browser settings and you can open any sites without knowing your spiritual insanity.

Modern proxy servers have comprehensive functionality for controlling and monitoring traffic - a good solution for offices and government agencies that need to protect employees from unwanted resources, as well as provide Internet access with additional authorization and different channel bandwidths for different users.

Whatever proxy use case you have, using the default gateway is in most cases more convenient. If only because some applications cannot work through a proxy.

Tun2Socks

Tun2Socks — free cross-platform project (GPL-3.0), written in Golang. The backbone of the development team is Chinese. The application does not have a graphical shell and is configured with simple parameters at startup. The name Tun2Socks (Tunnel to SOCKS) is interpreted as “a tunnel through a SOCKS proxy.” Why SOCKS when there is an HTTP proxy? The answer is simple: Tun2Socks can also work through an HTTP proxy, but the HTTP protocol does not support the transmission of UDP traffic. Most information, the delivery of which requires maximum speed, goes through UDP (audio and video calls, online games, as well as DNS queries that resolve human-readable names of network resources into IP addresses). Therefore, UDP support should not be underestimated.

The essence of Tun2Socks is to create a virtual network adapter, which the operating system will perceive as a regular network interface. All information received on such a virtual adapter will actually be transferred inside Tun2Socks, which will provide the necessary logic for further transfer of information to the proxy server.

Information about using the utility when launched with the parameter --help:

Usage of tun2socks:
  -device string
    	Use this device [driver://]name
  -fwmark int
    	Set firewall MARK (Linux only)
  -interface string
    	Use network INTERFACE (Linux/MacOS only)
  -loglevel string
    	Log level [debug|info|warn|error|silent] (default "info")
  -mtu int
    	Set device maximum transmission unit (MTU)
  -proxy string
    	Use this proxy [protocol://]host[:port]
  -stats string
    	HTTP statistic server listen address
  -token string
    	HTTP statistic server auth token
  -udp-timeout int
    	Set timeout for each UDP session
  -version
    	Show version information and quit

Everything may seem clear at first glance only to an experienced admin, or to someone who doesn’t really understand anything. When getting practically acquainted with Tun2Socks, the question arises: if a virtual network adapter is created in the system, how will it become the default gateway and whether it is necessary to manually set its address. Comes to the rescue documentation.

It makes no sense to duplicate the official description of the project and all the documentation here, so let’s get to the point - to the practical configuration of the gateway with an explanation of each step.

Windows

First you need to download the latest version of Tun2Socks. Binaries extend to releases page in the official Git repository of the project. Select one of the packages whose name begins with tun2socks-windows. If you have 64-bit Windows on old hardware, this will probably work for you tun2socks-windows-amd64.zip (since I have never seen ARM architecture on old Windows machines).

After downloading, unpack the archive to any convenient location.

Tun2Socks creates a virtual network adapter, but the driver for this (Wintun) needs to be downloaded separately. Here is the direct link to download Wintun version 0.11. I recommend this particular version, since in my case Tun2Socks v2.3.1 refused to work with newer versions. If desired, the latest driver release can be found on the official page. You only need one file from the entire archive wintun.dll, which must be taken from the desired directory depending on your operating system. In the case of amd64 architecture, the path to the required library looks like this: wintun/bin/amd64/wintun.dll. Place a suitable file wintun.dll to the directory where the Tun2Socks executable file is located.

Tun2Socks is launched with the values ​​passed in via the command line (the commands below must be executed with administrator rights). The command for a simple launch is as follows:

tun2socks-windows-amd64.exe -device tun://gatewaytun -proxy socks5://10.10.100.1:1080
  • tun2socks-windows-amd64.exe is the name of the Tun2Socks executable;

  • -device tun://gatewaytun defines the name of the new virtual network interface (gatewaytun);

  • -proxy socks5://10.10.100.1:1080 reports the protocol (in my case it is SOCKS5) and the proxy server address.

This is enough to create a new network interface in the system, but it won’t work as we want for now. To do this, you must manually assign an IP address to the new network interface and explain to the operating system that it is a gateway.

You can assign an IP address to the interface and specify a subnet mask through the standard Windows graphical interface, but we will use the benefits of the command line:

netsh interface ip set address name="gatewaytun" static 127.254.254.1 255.255.255.255

In the example, the virtual interface is assigned the address 127.254.254.1, but actually it could be anyone private an address from a subnet that, firstly, is not used by other network adapters of your operating system, and secondly, is not used on the local network of your business or home (otherwise local routing will be disrupted). In most cases, the example address will be a valid value (since the range 127.0.0.1/8 is used). In some tests, Windows 10 refused to apply such an address to the interface. If you also refused, use something like 10.254.254.1.So, we will assume that the address is assigned to the virtual network interface.

Now you need to tell the operating system the new interface as a gateway:

route add 0.0.0.0 mask 0.0.0.0 127.254.254.1

Attention! If the proxy server is not on a local network with the same subnet as one of your computer's network interfaces, i.e. access to the proxy server is carried out through an already existing gateway, you must leave access to the proxy server as is, otherwise the above configuration will not work - you must agree that trying to connect to the proxy server through the proxy server itself is absurd. In practice, this means that to connect to the proxy server you need to add another route:

route add 10.10.100.0 mask 255.255.255.0 10.10.5.25

The example shows a routing rule to a subnet 10.10.100.0/24, which should not go through a common gateway (gatewaytun), but through a network interface that has access to a device with the address 10.10.5.25 (which is the gateway to the desired subnet). This rule is true, firstly, if you need to maintain access to a local network subnet that is not directly accessible and, secondly, and more importantly, if the proxy server itself is located in a given subnet, through which all our traffic will go in the future.

For home use, where there are no local subnets and all that is required is a connection to a proxy server through an ISP, the above command is replaced by this:

route add 11.11.11.11 mask 255.255.255.255 10.10.5.25
  • 11.11.11.11 — Internet proxy server address;

  • 255.255.255.255 — a mask indicating that the rule includes only the proxy server address;

  • 10.10.5.25 — LAN gateway address provided to you by your ISP.

If you are using a SOCKS proxy (which supports UDP) rather than an HTTP one, in the virtual network interface settings you can specify the address of the DNS server through which we want to resolve domain names. This can be done both through the Windows graphical interface and through the command line:

netsh interface ip set dns "gatewaytun" static 1.1.1.1

In the example, the address 1.1.1.1 is the DNS server address.

The result is the following set of commands:

tun2socks-windows-amd64.exe -device tun://gatewaytun -proxy ПРОТОКОЛ_ПРОКСИ://АДРЕС_ПРОКСИ_СЕРВЕРА:ПОРТ
netsh interface ip set address name="gatewaytun" static 127.254.254.1 255.255.255.255
route add 0.0.0.0 mask 0.0.0.0 127.254.254.1

# Опционально. Для локальной сети предприятия.
route add СЕГМЕНТ_ЛОКАЛЬНОЙ_СЕТИ mask МАСКА_СЕГМЕНТА АДРЕСА_ШЛЮЗА_В_СЕГМЕНТ

# Опционально. При использовании прокси-сервера в интернете.
route add АДРЕС_ПРОКСИ_СЕРВЕРА mask 255.255.255.255 АДРЕС_ШЛЮЗА_ПРОВАЙДЕРА

# Опционально. DNS-сервер, если прокси-сервер умеет работать с UDP.
netsh interface ip set dns "gatewaytun" static АДРЕС_СЕРВЕРА_DNS

Most users may find it inconvenient to manually execute all the commands. Such people can experiment with automated scripts (batniks). For example, enter all the necessary commands into some start.bat and add it to startup. I'm not good at Windows batch files and permissions. As a parting word, I’ll just note that all commands must be executed with administrator rights. Perhaps someone will share a beautiful script in the comments.

Linux

Users of GNU/Linux (and other *nix systems) for the most part are more competent in matters of the command line and system settings, so in some places the explanations will be more sparse (especially since the essence of what is happening is already described in detail just above). Practical instructions are given using Debian as an example..

Binaries for Linux are available, among others, at releases page. For example, for Debian amd64 the option tun2socks-linux-amd64.zip. There is one file inside the archive. Once extracted, give it an executable flag (chmod +x tun2socks-linux-amd64) and put it in a convenient place, for example, /usr/sbin/. Additional drivers are not required to create a WireGuard tunnel in Linux - modern distributions support the technology at the kernel level.

All the commands below must be run with superuser rights.

The run command looks like this:

/usr/sbin/tun2socks-linux-amd64 -device tun://gatewaytun -proxy socks5://10.10.100.1:1080
  • -device tun://gatewaytun defines the name of the new virtual network interface (gatewaytun);

  • -proxy socks5://10.10.100.1:1080 reports the protocol (in my case it is SOCKS5) and the proxy server address.

After running Tun2Socks, a new network interface with the given name is created in the system. Now you need to adjust the routing rules:

# Присваиваем адрес новому интерфейсу
ip addr add 127.254.254.1/32 dev gatewaytun

# Включаем интерфейс
ip link set gatewaytun up

# Добавляем маршрут по умолчанию через новый интерфейс (спасибо @Aytuar)
ip route add default dev gatewaytun metric 50

# Опционально. Добавляем маршрут до прокси-сервера в локальной сети
ip route add АДРЕС_СЕТИ/ПРЕФИКС dev ИМЯ_ИНТЕРФЕЙСА_В_ЛОКАЛЬНОЙ_СЕТИ

# Опционально. Маршрут до прокси-сервера в интернете (наиболее вероятный вариант для дома)
ip route add АДРЕС_ПРОКСИ/32 dev ИМЯ_ИНТЕРФЕЙСА_В_СЕТИ_ПРОВАЙДЕРА

DNS settings on *nix systems are usually global, so there is no need to specify them explicitly for each interface. However, whoever needs it knows not only about /etc/resolv.conf, but also about the possibility of explicitly specifying a DNS server in the network connections config. We won't stop there.

Automation is the middle name of any administrator. For Debian I will write a systemd service that will launch Tun2Socks and raise the interface gatewaytun, and in the configuration of this network interface I will indicate the commands that need to be executed when it is turned on. If necessary, you can adapt this approach to other operating systems, taking into account their specifics.

The service file that will go to /etc/systemd/system/tun2socks.service:

[Unit]
Description=Tun2Socks gateway
After=network.target

[Service]
User=root
Type=idle
ExecStart=/usr/sbin/tun2socks-linux-amd64 -device tun://gatewaytun -proxy socks5://10.10.100.1:1080 & sleep 3; ip link set gatewaytun up
Restart=on-failure

[Install]
WantedBy=multi-user.target

Pay attention to the path to Tun2Socks and the proxy server address in the line ExecStart. Change these settings to suit your needs. After the ampersand there is a pause of three seconds, after which the new network interface is turned on. The pause is set in case of high system load to give time to create the interface before attempting to turn it on.

We indicate in /etc/network/interfaces interface parameters and additional instructions for execution after it is turned on. Lines are added to the end of the file:

allow-hotplug gatewaytun
iface gatewaytun inet static
address 127.254.254.0
netmask 255.255.255.255
post-up ip route add default dev gatewaytun metric 50

# Опционально. Добавляем маршрут до прокси-сервера в локальной сети
# post-up ip route add АДРЕС_СЕТИ/ПРЕФИКС dev ИМЯ_ИНТЕРФЕЙСА_В_ЛОКАЛЬНОЙ_СЕТИ

# Опционально. Маршрут до прокси-сервера в интернете (наиболее вероятный вариант для дома)
# post-up ip route add АДРЕС_ПРОКСИ/32 dev ИМЯ_ИНТЕРФЕЙСА_В_СЕТИ_ПРОВАЙДЕРА

# post-up <прочие правила, исполняемые после включения интерфейса (при надобности)>

Now that everything is ready, you can start and disable the gateway with two simple commands:

systemctl start tun2socks # ЗАПУСК
systemctl stop tun2socks # ОСТАНОВКА

If Tun2Socks is needed on an ongoing basis, the created service can be added to startup:

systemctl enable tun2socks

Afterword

The motivation for the article was the lack of adequate search results for queries like “gateway through a proxy”, “how to send all traffic through a proxy” and the like. I believe the material will be useful to the widest audience.

To be honest, I didn’t understand automation on Windows for a long time. It didn't start out of the box and let it rest. I don't like Windows, sorry. And how can you love it, if in order to execute a command from a bat file with administrator rights, you need to create a shortcut to this batch file and check the “Run with administrator rights” checkbox. Label and tick, Karl! And what’s more, the command to add a route still didn’t want to work.

Thank you for your attention.

Tags:
Hubs:
Всего голосов 15: ↑14 и ↓1 +13
Комментарии 14

Comments 14

I would add that the most interesting thing about tun2socks is that it can send traffic not only through regular socks5 proxies, but also through shadowsocks (inside tun2socks the kernel from go-shadowsocks is used2 - https://github.com/shadowsocks/go-shadowsocks2) - those. you get an almost full-fledged VPN - all traffic up to the proxy will be encrypted, unlike socks5, where you need to rely on higher-lying protocols. By the way, in the next release shadowsocks-rust (https://github.com/shadowsocks/shadowsocks-rust) similar functionality will be available (see. https://github.com/shadowsocks/shadowsocks-rust#tun-interface-client).

Thanks for the informative addition!

Greetings.

Have you considered options where, thanks to one very important government service, all unidentified and encrypted traffic will be blocked? In this regard, even i2p will become useless...

I see only two options: either a mesh network based on user wi-fi, since traffic over mobile networks is also controlled. Or some kind of cunning obfuscation, mimicking some allowed traffic.
We will not consider the third option in the form of exploitation of Starlink))

shadowsocks with obfs plugin allows you to mask traffic as, for example, http.

# Delete the old default gateway (if there was one))

It is always there, otherwise the packets have nowhere to go except to “shout” into the void (multicast, etc.).

And you don't need to delete it. You just need to add a new one with a metric higher than the priority of the current route.

Here is an example from my laptop that is connected to the network via cable and WiFi simultaneously to different routers.

default via 192.168.101.1 dev eth0 proto dhcp metric 100
default via 192.168.0.1 dev wlp2s0 proto dhcp metric 600 

All traffic goes through 192.168.101.1 because its metric is in priority (100 is the default).

So you just have to do this -

ip route add default dev gatewaytun metric 50
Local SOCKS5 via SSH tunnel to your VPS somewhere there:
ssh -Nf -D <произвольный номер порта> user@my-vps

Firefox + SwitchyOmega addon
SwitchyOmega is also available for chrome, haven’t tried it.

In SwitchyOmega we register a proxy for the required URLs:
SOCKS5, localhost, &lt;same port number>

I've been using it for many years. I’m too lazy to write a unit for a home desktop, I just stuck the script with this line into DE autoload.

Putty seems to be able to do this too.

So we won’t be able to run all traffic through a proxy; we’ll have to configure client applications to use it (as you showed), and the purpose of the article is precisely in the direction of all traffic. In cases of connecting to “your” VPS, and not to a proxy, you can use the same SSH VPN to redirect all traffic with the creation of an additional interface.

ssh root@remoteserver -w 0:0

Can. If, of course, it is necessary. In my opinion, it’s a rare case that all the traffic will certainly go to one proxy, and you can only drive it on client machines. It would be interesting to hear about real cases where this is exactly what is needed. After all, software for this is written and supported (last commit 8 hours ago), which means someone needs it.

I just decided to share my experience on a related topic in the comments, in case someone finds it useful.
A UFO flew in and published this inscription here

With version RouterOS v7.1rc3, it became possible to run Docker containers on some devices. Works very stable.

Label and tick, Carl!

contents of the file %path%\sudo.bat:

@powershell -Command "Start-Process cmd -Verb RunAs -ArgumentList '/k cd /d %cd% && %*'"

use :)

Your message is missing space 18+ :)

Hello. Tell me how to configure routing in my case? I have two interfaces on my machine. One wan port (eth0) receives settings from the upstream router. The second lan port (eth1) is where local network users connect. dhcp is configured (isc-dhcp-server) nat is configured. Tor installed. Now how can I direct all connections and dns traffic to tor using tun2socks? How to set up a route? Do I need to supplement existing iptables rules??

Only full-fledged users can leave comments. Sign in, Please.